<?php defined('SYSPATH') or die('No direct script access.');

/**
 * redis队列计划任务
 */
class Hooks_Enqueue_Task
{

    public static function queue_task()
    {
        //队列任务数据
        $list = DB::select()->from('queue_job')->execute()->as_array();
        if($list){
            foreach ($list as $val){
                $status = new Resque_Job_Status($val['token']);
                $args = json_decode($val['args'],true);
                if($status->get() == 4){
                    DB::delete('queue_job')->where('id','=',$val['id'])->execute();
                }
                if($status->get() == 3){
                    if($val['in_num'] < 3){
                        Hooks_Enqueue_Queue::handle($val['queue_name'],$val['job_name'],$args,$val['id']);
                        //改变任务状态
                        DB::update('queue_job')->set(array('status'=>1,'in_num'=>($val['in_num']+1)))
                            ->where('id','=',$val['id'])->execute();
                    }else{
                        DB::update('queue_job')->set(array('status'=>3))
                            ->where('id','=',$val['id'])->execute();
                    }
                }
                if($status->get() == 1 && (time() - $val['create_time']) >= 180){
                    Hooks_Enqueue_Queue::del_job($val['queue_name'],$val['job_name']);
                    if($val['in_num'] < 3){
                        Hooks_Enqueue_Queue::handle($val['queue_name'],$val['job_name'],$args,$val['id']);
                        DB::update('queue_job')->set(array('in_num'=>($val['in_num']+1)))
                            ->where('id','=',$val['id'])->execute();
                    }
                }
            }
        }
    }
}